package cn.bxshey.modules_commodity.service.impl;

import cn.bxshey.general.enums.ResultEnum;
import cn.bxshey.general.exception.BusinessException;
import cn.bxshey.modules_commodity.dto.commodity.*;
import cn.bxshey.modules_commodity.mapper.CommodityMapper;
import cn.bxshey.modules_commodity.mapper.CouponsMapper;
import cn.bxshey.modules_commodity.service.CommodityService;
import cn.bxshey.modules_commodity.service.CouponsService;
import cn.bxshey.modules_commodity.strategy.coupons.Strategy;
import cn.bxshey.modules_commodity.strategy.coupons.StrategyFactory;
import cn.bxshey.modules_commodity.vo.commodity.CartDetailVO;
import cn.bxshey.modules_commodity.vo.commodity.DetailVO;
import cn.bxshey.modules_commodity.vo.commodity.PaginatedQueriesVO;
import cn.bxshey.modules_commodity.vo.commodity.SettlementSpecificationVO;
import cn.bxshey.redis.constant.RedisConstant;
import cn.bxshey.redis.utils.RedisUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @作者：不想说话而已
 * @Date：2024/1/30 14:41
 * 商品业务
 */

@Service
@Transactional
public class CommodityServiceImpl implements CommodityService {

    @Resource
    CommodityMapper commodityMapper;

    @Resource
    CouponsMapper couponsMapper;

    @Resource
    CouponsService couponsService;

    @Resource
    RedisUtils redisUtils;

    /**
     * 商品--分页查询
     *
     * @param dto 分页查询参数
     * @return 分页商品数据
     */
    @Override
    public List<PaginatedQueriesVO> queryPage(PaginatedQueriesDTO dto) {
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        return commodityMapper.queryPage(dto);
    }

    /**
     * 商品--新增
     *
     * @param dto 新增参数
     * @return 成功个数
     */
    @Override
    public Integer addCommodity(AddCommodityDTO dto) {
        String id = UUID.randomUUID().toString();
        commodityMapper.addCommodity(id, dto);
        dto.getCommoditySpecification().setCommodityId(id);
        return commodityMapper.addCommoditySpecification(dto.getCommoditySpecification());
    }

    /**
     * 商品--更新商品(不更新规格)
     *
     * @param dto 新增参数
     * @return 成功个数
     */
    @Override
    public Integer updateCommodity(UpdateCommodityDTO dto) {
        return commodityMapper.updateCommodity(dto);
    }

    /**
     * 商品--更新商品规格
     *
     * @param dto 更新参数
     * @return 成功个数
     */
    @Override
    public Integer updateCommoditySpecification(UpdateCommoditySpecificationDto dto) {
        return commodityMapper.updateCommoditySpecification(dto);
    }

    /**
     * 商品--新增商品规格
     *
     * @param dto 新增参数
     * @return 成功个数
     */
    @Override
    public Integer addCommoditySpecification(AddCommoditySpecificationDTO dto) {
        return commodityMapper.addCommoditySpecification(dto);
    }

    /**
     * 商品--根据id查询商品内容详情
     *
     * @param id 商品id
     * @return 商品详情内容
     */
    @Override
    public DetailVO commodityById(String id) {
        return commodityMapper.commodityById(id);
    }

    /**
     * 商品--加入购物车
     *
     * @param id  用户id
     * @param dto 商品id、规格id、数量
     * @return 商品详情内容
     */
    @Override
    public Long addCart(String id, AddCartDTO dto) throws JsonProcessingException {
        Map<String, Object> info = new HashMap<>();
        info.put("num", dto.getCommodityNum());
        info.put("commodityId", dto.getCommodityId());
        info.put("commoditySpecificationId", dto.getCommoditySpecificationId());
        //返回购物车商品总数
        return redisUtils.setHash(RedisConstant.CART.concat(id), dto.getCommoditySpecificationId(), info);

    }

    /**
     * 商品--获取购物车信息
     *
     * @param id 用户id
     * @return 商品详情内容
     */
    @Override
    public List<CartDetailVO> cartDetail(Long id) throws IOException {
        //获取购物车关键信息
        List<String> cartInfo = redisUtils.getHash(RedisConstant.CART, id);
        ObjectMapper mapper = new ObjectMapper();
        //
        List<Map<String, Object>> info = new ArrayList<>();
        //商品规格id列表
        List<String> specificationIdList = new ArrayList<>();
        //购物车中所有商品的关键信息
        cartInfo.forEach(s -> {
            try {
                Map<String, Object> map = mapper.readValue(s, new TypeReference<Map<String, Object>>() {
                });
                specificationIdList.add(String.valueOf(map.get("commoditySpecificationId")));
                info.add(map);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        });
        if (specificationIdList.size() < 1) {
            return new ArrayList<>();
        }
        List<CartDetailVO> cartDetailVO = commodityMapper.commodityList(specificationIdList);
        for (int index = 0; index < cartDetailVO.size(); index++) {
            for (Map<String, Object> i : info) {
                //如果商品id和商品规格id相符
                if (cartDetailVO.get(index).getCart_commodity_id().equals(i.get("commodityId"))
                        &&
                        cartDetailVO.get(index).getCart_commodity_specification_id().equals(Long.valueOf(i.get("commoditySpecificationId").toString()))
                ) {
                    cartDetailVO.get(index).setCart_commodity_num(Integer.valueOf(i.get("num").toString()));
                    System.out.println(cartDetailVO);
                    break;
                }
            }
        }
        return cartDetailVO;
    }

    /**
     * 商品--结算
     *
     * @param id             用户id
     * @param settlementDTOS 商品规格id、商品数量、优惠卷
     * @return 值
     */
    @Override
    public Object settlement(Long id, List<SettlementDTO> settlementDTOS) {

        //获取商品规格列表等信息
        List<SettlementSpecificationVO> cartDetailVOS = commodityMapper.commoditySpecificationList(settlementDTOS);

        //存储每次价格累加的list列表
        List<BigDecimal> totalPrice = new ArrayList<>();
        for (SettlementDTO cart : settlementDTOS) {
            for (SettlementSpecificationVO cartDetail : cartDetailVOS) {
                //如果库存不足
                if (cart.getCommoditySpecificationId().equals(cartDetail.getCommodity_specification_id()) && cart.getNum() > cartDetail.getCommodity_specification_inventory()) {
                    throw new BusinessException(ResultEnum.ERROR_INVENTORY);
                }

                //如果商品id和商品规格id和购物车的商品信息相符合
                if (cart.getCommoditySpecificationId().equals(cartDetail.getCommodity_specification_id())) {

                    //金额运算--如果list长度为0表明此次为第一次价格操作
                    totalPrice.add(cartDetail.getCommodity_specification_price().add(totalPrice.size() < 1 ? BigDecimal.ZERO : (totalPrice.get(totalPrice.size() - 1))).multiply(BigDecimal.valueOf(cart.getNum())));

                    //该商品结算时是否添加有优惠卷
                    Optional.ofNullable(Objects.isNull(cart.getCoupons()) ? null : true).ifPresent(s -> {

                        for (CouponsDTO couponsDTO : cart.getCoupons()) {
                            System.err.println(couponsDTO);
                            //获取对应的商品策略
                            if (!(StrategyFactory.is(couponsDTO.getType()))) {
                                break;
                            }
                            Strategy coupon = StrategyFactory.getStrategy(couponsDTO.getType());

//                            //记录最新金额
//                            totalPrice.add(coupon.calculatePrice(id, couponsDTO.getId(), cartDetail.getCommodity_id()));

                        }

                    });

                    //直接退出当前循环，进入下一个商品的循环
                    break;
                }
            }
        }

        return totalPrice.size() > 0 ? totalPrice.get(totalPrice.size() - 1) : null;

    }


}
